package com.gaogzhen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaogzhen.domain.WorkIssue;
import com.gaogzhen.dto.UserDto;
import com.gaogzhen.feigh.UserServiceFeign;
import com.gaogzhen.mapper.WorkIssueMapper;
import com.gaogzhen.service.WorkIssueService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class WorkIssueServiceImpl extends ServiceImpl<WorkIssueMapper, WorkIssue> implements WorkIssueService{

    @Autowired
    private UserServiceFeign userServiceFeign;

    @Override
    public Page<WorkIssue> findByPage(Page<WorkIssue> page, String startTime, String endTime, Integer status) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<WorkIssue> workIssuePage = page(page, Wrappers.lambdaQuery(WorkIssue.class)
                .between(StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime), WorkIssue::getCreated, startTime, endTime + " 23:59:59")
                .eq(ObjectUtils.isNotEmpty(status), WorkIssue::getStatus, status)
        );
        List<WorkIssue> workIssues = workIssuePage.getRecords();
        if (CollectionUtils.isEmpty(workIssues)) {
            return workIssuePage;
        }
        // 远程调用member-service 获取用户的简要信息
        // 1 收集用户ids
        List<Long> ids = workIssues.stream().map(WorkIssue::getUserId).collect(Collectors.toList());
        // 2 远程调用
        Map<Long, UserDto> userDtoMap = userServiceFeign.getBriefUsers(ids, null, null);
        workIssues.forEach(workIssue -> {
            UserDto userDto = userDtoMap.get(workIssue.getUserId());
            workIssue.setUsername(userDto == null ? "测试用户": userDto.getUsername());
            workIssue.setRealName(userDto == null ? "测试用户": userDto.getUsername());
        });
        return workIssuePage;
    }

    @Override
    public WorkIssue info(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new RuntimeException("查询工单id能为空");
        }
        return getById(Long.valueOf(id));
    }

    @Override
    public void updateWorkIssue(WorkIssue workIssue) {
        // 从安全的上下文里面获取用户的ud
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long answerUserId = null;
        if(authentication != null){
            // userId ->Long  anonymousUser
            String s = authentication.getPrincipal().toString();
            if(!StringUtils.equals("anonymousUser", s)){
                //是因为用户没有登录访问时,就是这个用户
                answerUserId = Long.valueOf(s);
            }
        }
        // 设置回复人id
        workIssue.setAnswerUserId(answerUserId);
        boolean update = updateById(workIssue);
        if (!update) {
            throw new RuntimeException("更新客服工单失败！");
        }
    }

    @Override
    public Page<WorkIssue> getIssuesByUserId(Long userId, Page<WorkIssue> page) {
        return page(page, new LambdaQueryWrapper<WorkIssue>()
                            .eq(WorkIssue::getUserId, userId)
        );
    }
}
